package com.cskaoyan.service.vx;


import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.param.FileParam;
import com.cskaoyan.bean.po.StoragePO;
import com.cskaoyan.mapper.wxMapper.MarketStorageMapper;
import com.cskaoyan.util.RandomNameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

import static com.cskaoyan.bean.param.FileParam.BASE_PATH;

@Service
public class WxStorageServiceImpl implements WxStorageService {
    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Override
    public BaseRespVo uploadPicture(MultipartFile file) {
        StoragePO storagePO = new StoragePO();

        String name = RandomNameUtils.getName(Objects.requireNonNull(file.getOriginalFilename()));
        storagePO.setKey(name);
        storagePO.setAddTime(new Date());
        storagePO.setName(file.getOriginalFilename());
        storagePO.setSize((int) file.getSize());
        storagePO.setAdd_time(storagePO.getAddTime());
        storagePO.setUpdateTime(storagePO.getAddTime());
        storagePO.setUpdate_time(storagePO.getUpdateTime());
        storagePO.setType(file.getContentType());
        storagePO.setDeleted(false);
        String url = FileParam.PIC_APP + name;
        storagePO.setUrl(url);
        String property = System.getProperty("os.name");
        File path = null;
        if (property.contains("Windows")) {
            path = new File(BASE_PATH + FileParam.PATH_NAME_WINDOWS,name);
        } else if (property.contains("Mac")) {
            path = new File(BASE_PATH + FileParam.PATH_NAME_MAC,name);
        }
        try {

            assert path != null;
            System.out.println(name);
            file.transferTo(path);
            //file.transferTo(new File(BASE_PATH+"/src/main/resources/static/",name));

        } catch (IOException e) {
            e.printStackTrace();
        }
        int affectRows = marketStorageMapper.insertWxImage(storagePO);
        storagePO.setUrl(FileParam.URL_PRE + storagePO.getUrl());
        return BaseRespVo.ok(storagePO);
    }
}
